<?php

namespace app\services;

use plugin\admin\app\model\Equity;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserLevel;
use plugin\admin\app\model\UserLevelLog;
use plugin\admin\app\model\UserProperty;
use plugin\admin\app\model\UserRecommendTeam;
use plugin\admin\app\model\UserTeam;

class UserLevelService
{
    public static function list()
    {
        // 获取所有的 UserLevel 数据
        $res = UserLevel::all()->toArray();

        // 获取所有的 Equity 数据
        $allEquities = Equity::all()->keyBy('id')->toArray();

        foreach ($res as $key => $value) {
            $res[$key]['icon'] = full_url($value['icon']);
            $res[$key]['name'] = get_current_language() == 'zh' ? $value['name'] : $value['en_name'];
            // 如果 equity 存在，进行处理
            if (!empty($value['equity'])) {
                // 用逗号分隔 equity 字段
                $equityIds = explode(',', $value['equity']);

                // 查找对应的 Equity 数据
                $equitys = [];
                foreach ($equityIds as $equityId) {
                    if (isset($allEquities[$equityId])) {
                        $equity = $allEquities[$equityId];
                        $equity['icon'] = full_url($equity['icon']);
                        $equity['name'] = get_current_language() == 'zh' ? $equity['name'] : $equity['en_name'];
                        $equity['desc'] = get_current_language() == 'zh' ? $equity['desc'] : $equity['en_desc'];
                        $equitys[] = $equity;
                    }
                }

                // 添加新的 equitys 属性
                $res[$key]['equitys'] = $equitys;
            } else {
                // 如果没有 equity，设置为空数组
                $res[$key]['equitys'] = [];
            }
        }

        return $res;
    }

    public static function equity()
    {
        $res = Equity::all()->toArray();

        foreach ($res as $key=>$value) {
            $res[$key]['icon'] = full_url($value['icon']);
            $res[$key]['name'] = get_current_language() == 'zh' ? $value['name'] : $value['en_name'];
            $res[$key]['desc'] = get_current_language() == 'zh' ? $value['desc'] : $value['en_desc'];
        }

        return $res;
    }

    public static function getLevelInfo($levelId)
    {
        $info = UserLevel::where('id', $levelId)->first();

        $info['icon'] = full_url($info['icon']);
        $equityIds = explode(',', $info['equity']);
        $equityInfo = Equity::whereIn('id', $equityIds)->get()->toArray();
        foreach ($equityInfo as $key => $value) {
            $equityInfo[$key]['icon'] = full_url($value['icon']);
            $equityInfo[$key]['name'] = get_current_language() == 'zh' ? $value['name'] : $value['en_name'];
            $equityInfo[$key]['desc'] = get_current_language() == 'zh' ? $value['desc'] : $value['en_desc'];
        }
        $info['equitys'] = $equityInfo;
        return $info;
    }

    public static function levelUp($userId, $level, $remark = '')
    {
        $user = User::find($userId);

        if ($user->level < $level) {
            UserLevelLog::insert([
               'user_id' => $userId,
               'level' => $level,
                'created_time' => date('Y-m-d H:i:s'),
                'remark' => $remark
            ]);
            $user->level = $level;
            $user->save();
        }
    }

    /**
     * 伞下成员满足条件，升级
     *
     * @param $userId
     * @return int|void
     */
    public static function levelUpCheck($userId)
    {
        $userInfo = User::where('id', $userId)->first();

        $propertyInfo = UserProperty::where('user_id', $userId)->first();   //累计充值金额
        $consume = Order::where('user_id', $userId)->whereNotNull('pay_time')->where('refund_status', 0)->sum('price');

        $balance = bcadd($propertyInfo['recharge_balance'], $consume, 2);

        $levelInfo = UserLevel::where('recharge_balance', '<=', $balance)->orderBy('recharge_balance', 'desc')->first();

        if ($levelInfo['id'] > $userInfo['level']) {
            self::levelUp($userId, $levelInfo['id'], '累计充值与消费金额达到' . $levelInfo['recharge_balance']);
        }
    }

    /**
     * 两个月没有购买抱单礼包，等级状态设置为异常
     * 三个月没有购买抱单礼包，等级设置为社员
     *
     * @return void
     */
    public static function levelStatusCheck()
    {
        $levelUsers = User::where('level', '>', 1)->get()->toArray();

        foreach ($levelUsers as $levelUser) {
            $threeMonthCount = OrderService::getRangeTimeGiftOrderCount(date('Y-m-01', strtotime('-3 months')), date('Y-m-t', strtotime('-1 months')), $levelUser['id']);

            $twoMonthCount = OrderService::getRangeTimeGiftOrderCount(date('Y-m-01', strtotime('-3 months')), date('Y-m-t', strtotime('-1 months')), $levelUser['id']);

            if ($threeMonthCount == 0) {
                User::where('id', $levelUser['id'])->update(['level' => 1]);
            }

            if ($twoMonthCount == 0) {
                User::where('id', $levelUser['id'])->update(['level_status' => User::LEVEL_STATUS_EXCEPTION]);
            }
        }
    }
}